package com.bbcare.followup.plat.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.SeqUtil;
import com.bbcare.comm.ToolUtils;
import com.bbcare.followup.plat.service.IPatientFollowService;

/**
 * @name: 患者随访相关处理类
 * @author: DemonLee
 * @createTime: 2017.7.11
 * @description: 患者随访相关操作
 * @modify:
 *
 */
@Controller
@RequestMapping("/service/patientFollow")
public class PatientFollowController {
    private final Log logger = LogFactory.getLog(PatientFollowController.class);

    @Autowired
    private IPatientFollowService patientFollowService;

    // 查询随访评估量表内容模板
    @ResponseBody
    @RequestMapping("/queryFuAssessContTmpl")
    public ResultModel<Object> getFuAssessContTmpl(@RequestBody String jsonStr) throws Exception {
        logger.warn("in getFuAssessContTmpl----arg==" + jsonStr);

        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        String busiId = requestParam.getString("busiId");
        if (StringUtils.isBlank(busiId)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "参数校验失败，业务id不能为空");
        }
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("busiId", busiId);
        Map<String, Object> outMap = patientFollowService.getPatientFollowContTempl(paramMap);
        return new ResultModel<Object>(outMap);
    }

    // 随访评估量表内容提交
    @ResponseBody
    @RequestMapping("/submitPtFuAssessCont")
    public ResultModel<Map<String, Object>> savePtFuAssessCont(@RequestBody String arg, HttpServletRequest request)
            throws Exception {
        logger.warn("in savePtFuAssessCont----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }
        JSONObject jsonOprInfo = jsonData.getJSONObject(Constants.INF_INPUTPARAM_OPRINFO_FIELD);
        if (null == jsonOprInfo) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无oprInfo节点！"));
        }
        JSONObject jsonBusiInfo = jsonData.getJSONObject("busiInfo");
        if (null == jsonBusiInfo) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无busiInfo节点！"));
        }
        Map<String, Object> quesMap = (JSONObject) jsonData.get("questiones");
        if (MapUtils.isEmpty(quesMap)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无问题答案节点或为空！"));
        }

        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String authorName = (String) sessionMap.get("authorName");// 登录账号医生姓名
        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        Map<String, Object> oprInfoMap = jsonOprInfo;

        // 入参校验
        String opCode = jsonOprInfo.getString("opCode");
        if (StringUtils.isBlank(opCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，操作编码为空！"));
        }
        String opType = jsonOprInfo.getString("opType");
        if (StringUtils.isBlank(opType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，操作类型为空！"));
        }
        String opNote = jsonOprInfo.getString("opNote");
        if (StringUtils.isBlank(opNote)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，操作备注为空！"));
        }
        // 来源渠道，入参若无，则默认门诊渠道
        String sourceType = jsonOprInfo.getString("sourceType");
        if (StringUtils.isBlank(sourceType)) {
            sourceType = Constants.PATIENT_SOURCE_TYPE_DOOR;
        }
        oprInfoMap.put("sourceType", sourceType);

        // 任务信息
        String busiId = jsonBusiInfo.getString("busiId");
        if (StringUtils.isBlank(busiId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，评估业务Id为空！"));
        }
        String patientId = jsonBusiInfo.getString("patientId");
        if (StringUtils.isBlank(patientId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，患者id为空！"));
        }
        String tmplVerInfo = jsonBusiInfo.getString("tmplVerInfo");
        if (StringUtils.isBlank(tmplVerInfo)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，模板id为空！"));
        }

        oprInfoMap.put("authorName", authorName);
        oprInfoMap.put("updateTime", DateUtil.getTimeString(DateUtil.getSysDateA()));// 操作时间
        oprInfoMap.put("authorId", authorId);
        oprInfoMap.put("updateAccept", SeqUtil.getSeqNo(Constants.SEQ_NO_FOR_SYSTEMID));// 操作流水
        oprInfoMap.put("tenantId", tenantId);
        jsonData.put(Constants.INF_INPUTPARAM_OPRINFO_FIELD, oprInfoMap);

        Map<String, Object> retout = patientFollowService.savePtAssessContent(jsonData);
        return new ResultModel<Map<String, Object>>(retout);
    }

    // 查询随访评估量表某次记录详情
    @ResponseBody
    @RequestMapping("/queryPtFuAssessInfo")
    public ResultModel<Object> getPtFuAssessInfo(@RequestBody String jsonStr) throws Exception {
        logger.warn("in getPtFuAssessInfo----arg==" + jsonStr);

        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        String busiId = requestParam.getString("busiId");
        if (StringUtils.isBlank(busiId)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "参数校验失败，业务id不能为空");
        }
        String patientId = requestParam.getString("patientId");
        if (StringUtils.isBlank(patientId)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "参数校验失败，患者id不能为空");
        }
        String updateAccept = requestParam.getString("updateAccept");
        if (StringUtils.isBlank(updateAccept)) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "参数校验失败，操作流水不能为空");
        }
        Map<String, Object> outMap = patientFollowService.getPtFuAssessContInfo(requestParam);
        return new ResultModel<Object>(outMap);
    }

    // 查询随访评估量表记录list
    @ResponseBody
    @RequestMapping("/queryPtFuAssesList")
    public Map<String, Object> listPtFuAsses(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.warn("in listPtFuAsses----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        String busiId = jsonData.getString("busiId");
        if (StringUtils.isEmpty(busiId)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，业务模板id为空！"));
        }
        String opCode = jsonData.getString("opCode");
        if (StringUtils.isEmpty(opCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作编码为空！"));
        }
        String opType = jsonData.getString("opType");
        if (StringUtils.isEmpty(opType)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，操作类型为空！"));
        }
        paramMap.put("opCode", opCode);
        paramMap.put("busiId", busiId);
        paramMap.put("opType", opType);

        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (!StringUtils.isEmpty(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (!StringUtils.isEmpty(userName)) {
            paramMap.put("userName", userName + "%");
        }
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);

        // 增加队列id和患者来源
        paramMap.put("qryEndTime", jsonData.getString("qryEndTime"));
        paramMap.put("qryStartTime", jsonData.getString("qryStartTime"));

        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }

        Map<String, Object> retMap = patientFollowService.listPtFuAsses(paramMap);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }
        retMap.put("success", true);

        return retMap;
    }

    // 查询患者样本采集状态列表list
    @ResponseBody
    @RequestMapping("/qryPtSampleList")
    public Map<String, Object> listPtSample(@RequestBody String arg, HttpServletRequest request) throws Exception {
        logger.warn("in listPtSample----arg==" + arg);

        JSONObject jsonArg = null;
        try {
            jsonArg = JSON.parseObject(arg);
        } catch (Exception ex) {
            ex.printStackTrace();
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_FORMAT_ERROR, "入参格式错误，非json格式！"));
        }

        JSONObject jsonData = jsonArg.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD);
        if (null == jsonData) {
            // 前台必须传data节点，否则报错返回
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！"));
        }

        HashMap<String, Object> paramMap = new HashMap<String, Object>();
        // 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

        paramMap.put("authorId", authorId);
        paramMap.put("tenantId", tenantId);

        String sampleCode = jsonData.getString("sampleCode");
        if (StringUtils.isEmpty(sampleCode)) {
            throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无样本采集编码！"));
        }
        paramMap.put("sampleCode", sampleCode);
        String phoneNo = jsonData.getString("phoneNum");
        String userName = jsonData.getString("patientName");// 可以是姓氏或姓名
        int page = jsonData.getIntValue("page");
        int rows = jsonData.getIntValue("rows");
        page = page == 0 ? 1 : page;
        rows = rows == 0 ? 20 : rows;

        if (!StringUtils.isEmpty(phoneNo)) {
            paramMap.put("phoneNo", phoneNo);
        }
        if (!StringUtils.isEmpty(userName)) {
            paramMap.put("userName", userName + "%");
        }
        paramMap.put("start", (page - 1) * rows);
        paramMap.put("end", rows);

        // 增加队列id和患者来源
        if (!StringUtils.isEmpty(jsonData.getString("hisNo"))) {
            paramMap.put("hisNo", jsonData.getString("hisNo"));
        }
        if (!StringUtils.isEmpty(jsonData.getString("queueId"))) {
            paramMap.put("queueId", jsonData.getString("queueId"));
        }

        // 针对Datatable特殊处理
        String jsonStr = jsonData.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonStr)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonStr);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("start", jsonTable.getIntValue("start"));
            paramMap.put("end", jsonTable.getIntValue("length"));
        }

        Map<String, Object> retMap = patientFollowService.listPtSample(paramMap);
        // 针对Datatable特殊处理
        if (!StringUtils.isEmpty(jsonStr)) {
            retMap.put("draw", draw);
            retMap.put("recordsTotal", retMap.get("total"));
            retMap.put("recordsFiltered", retMap.get("total"));
        }
        retMap.put("success", true);

        return retMap;
    }

    // 查询医院科室基本信息
    @ResponseBody
    @RequestMapping("/queryHospitalInfo")
    public ResultModel<Object> getHospitalInfo(@RequestBody String jsonStr, HttpServletRequest request)
            throws Exception {
        logger.warn("in getHospitalInfo----arg==" + jsonStr);

        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); // 统一节点处理
        if (null == requestParam) {
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
        }
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        Map<String, Object> mapIn = new HashMap<String, Object>();
        mapIn.put("deptId", sessionMap.get("deptId"));
        mapIn.put("tenantId", sessionMap.get("tenantId"));
        Map<String, Object> outMap = patientFollowService.getHospitalInfo(mapIn);
        return new ResultModel<Object>(outMap);
    }

}
